package uia.alumni.profile;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.form.Form;
import uia.alumni.form.FormField;
import uia.alumni.web.Command;
import static uia.alumni.form.FieldType.*;
import static uia.alumni.profile.Constants.*;
import static uia.alumni.web.Constants.*;

/**
 * Saves profile data if Fields are valid.
 * @author Simon Zimmermann
 */
public class SaveProfile extends Command {

    public static final String SERVLET_NAME = "profile.save";
    @PersistenceUnit(name = PERSISTENCE_UNIT)
    private EntityManagerFactory emf;
    @Resource
    private UserTransaction tx;

    public SaveProfile() {
        super(Role.member);
    }

    /**
     * Save profile data from the EditProfile form.
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        boolean success = false;
        String from = request.getParameter("from");

        try {
            tx.begin();
            EntityManager em = emf.createEntityManager();
            User user = getUser(em, request);

            // Get Values and Check their Content
            Form form = new Form(request);
            FormField fullname = form.newField(FULLNAME, TEXT);
            FormField email = form.newField(MAIL, EMAIL);
            FormField address = form.newField(ADDRESS, TEXT);
            FormField phone = form.newField(PHONE, PHONENUMBER);
            FormField description = form.newField(DESCRIPTION, TEXT);


            // Set Extra options
            address.setOptional(true);
            phone.setOptional(true);
            description.setOptional(true);


            // Check if the input is Valid
            if (form.isValid() && user != null) {
                ProfileManager pm = new ProfileManager(request, em);
                String mail = email.getFieldValue();
                if (pm.isUniqueEmail(mail) || user.getEmail().equals(mail)) { //Check if new Email is unique

                    user.setFullName(fullname.getFieldValue());
                    user.setEmail(email.getFieldValue());
                    user.setDescription(description.getFieldValue());
                    user.setPhone(phone.getFieldValue());
                    user.setAddress(address.getFieldValue());

                    // If admin. We should also update roles
                    if (isAdmin(em, request)) {
                        for (Role r : Role.values()) {
                            if ((request.getParameter(r.name())) != null) {
                                user.addRole(r);
                                if(DEBUG) addMessage(request, r.name()+": Added");
                            } else {
                                user.removeRole(r);
                                if(DEBUG) addMessage(request, r.name()+": removed");
                            }
                            if(DEBUG) addMessage(request,"Is Admin");
                        }
                    } else {
                        if(DEBUG) addMessage(request,"Is NOT Admin");
                    }
                    tx.commit();
                    request.setAttribute(USER, user);
                    success = true;
                } else {
                    addFormErrors(request, form.addError("Email Not Unique"));
                }
            } // If form is invalid, Add form errors to FORMERRORS.
            else {
                addFormErrors(request, form.getErrors());
            }

        } catch (Exception e) {
            log("Save profile failed", e);
            addMessage(request, "Save profile failed, because" + e.getMessage());
        }
        if (success) {
            forwardTo(ViewProfile.SERVLET_NAME, request, response);
        } else if (from == null) {
            forwardTo(EditProfile.SERVLET_NAME, request, response);
        }
        forwardTo(from, request, response); //Return to the servlet who sent me.
    }
    public final static long serialVersionUID = 1;
}
